﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace DAO
{
    class ConnectDB
    {
        
        SqlConnection con = new SqlConnection();
        string ketnoi = ConfigurationManager.ConnectionStrings["project"].ConnectionString;
        public ConnectDB()
        {
            con.ConnectionString = ketnoi;
            if (con.State == ConnectionState.Closed)
                con.Open();
        }
        public void Close()
        {
            con.Dispose();
        }
        public DataTable LayDuLieu(string sql)
        {
            SqlCommand command = new SqlCommand(sql, con);
            //command.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            DataTable dt = new DataTable();
            adapter.Fill(dt);
            command.Dispose();
            adapter.Dispose();
            dt.Dispose();
            return dt;
        }

        public DataTable LayDuLieu(string sql, string[] name, object[] value, int Nparameter)
        {
            SqlCommand command = new SqlCommand(sql, con);
            //command.CommandType = CommandType.StoredProcedure;
            for (int i = 0; i < Nparameter; i++)
            {
                command.Parameters.AddWithValue(name[i], value[i]);
            }
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            DataTable dt = new DataTable();
            adapter.Fill(dt);
            command.Dispose();
            adapter.Dispose();
            dt.Dispose();
            return dt;
        }
        public void excute(string sql)
        {
            SqlCommand command = new SqlCommand(sql, con);
            //command.CommandType = CommandType.StoredProcedure;
            command.Dispose();
            command.ExecuteNonQuery();
        }
        public int Update(string sql)
        {
            SqlCommand command = new SqlCommand(sql, con);
            //command.CommandType = CommandType.StoredProcedure;
            command.Dispose();
            return command.ExecuteNonQuery();
        }

        public int Update(string sql, string[] name, object[] value, int Nparameter)
        {
            SqlCommand command = new SqlCommand(sql, con);
            //command.CommandType = CommandType.StoredProcedure;
            for (int i = 0; i < Nparameter; i++)
            {
                command.Parameters.AddWithValue(name[i], value[i]);
            }
            command.Dispose();
            return command.ExecuteNonQuery();
        }
    }
}
